﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRM.Business
{
   public class ContentInfo
    {
       //首页获取新闻列表
       public static List<CRM.Model.ContentList> GetNewsList(int n)
       {
           try
           {
               var db = new CRM.DataLayer.CRMDateEntities();
               var query = (from p in db.ContentInfor
                              where p.type == "新闻动态"
                              orderby p.date descending
                              select new CRM.Model.ContentList() 
                              { 
                                  Id=p.ID,
                                  Title=p.title,
                                  ImgPath=p.image,
                              }).Take(n).ToList();
               List<CRM.Model.ContentList> result = new List<Model.ContentList>();
               foreach (var item in query)
               {
                   item.Title = CutString(item.Title,26);
                   result.Add(item);
               }
               return result.ToList();
           }
           catch (Exception)
           {               
               return null;
           }
       }
       /// <summary>
       /// 显示规定长度的标题字符串，多余部分截掉用..代替
       /// </summary>
       /// <param name="str">str代表title字符串</param>
       /// <param name="n">n代表标题显示的最大长度</param>
       /// <returns></returns>
       public static string CutString(string str, int n)
       {
           ///格式化字符串长度，超出部分显示省略号,区分汉字跟字母。汉字2个字节，字母数字一个字节
           ///
           string temp = string.Empty;
           if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串
           {
               return str;
           }
           else
           {
               int t = 0;
               char[] q = str.ToCharArray();
               for (int i = 0; i < q.Length && t < n; i++)
               {
                   if ((int)q[i] >= 0x4e00 && (int)q[i] <= 0x9fa5)//是否汉字
                   {
                       temp += q[i];
                       t += 2;
                   }
                   else
                   {
                       temp += q[i];
                       t++;
                   }
               }
               return (temp + "..");
           }
       }
    }
}
